#!/usr/bin/env -S node -r ./livescript-transform-implicit-async/register

require! <[klaw path chalk ./git]>
require! {
  \fs-extra : fs
}



module.exports = (argv)~>
  {template} = argv.config
  {cwd} = argv

  exist = []
  new Promise (resolve)!~>
    klaw(
      template
      filter:(item)~>
        if item.slice(template.length+1).startsWith('.git')
          return false
        return true
    ).on(
      \data
      (item)!~>
        if item.stats.isDirectory!
          return
        p = item.path
        t = path.join argv.cwd, p.slice(template.length+1)
        if await fs.exists(t)
          {oid} = await git.hashBlob({
            object:await fs.readFile(t)
          })

          oid-now = await git.hashBlob({
            object:await fs.readFile(p)
          })

          if oid-now.oid == oid
            return

          try
            await git.expandOid({
              dir: template
              oid
            })
          catch err
            if \ShortOidNotFound == err.code
              exist.push t
            else
              console.trace!
              console.log err
            return
        await fs.copy(
          p
          t
        )
    ).on(
      \end
      !~>
        oid = await git.resolve-ref {
          ref:\HEAD
          dir:template
        }
        await fs.outputFile path.join(cwd, "6du/template.head"), oid
        if exist.length
          console.log chalk.greenBright(
            "以下文件您修改过，跳过更新 :"
          )
          console.log chalk.green "  "+exist.join '\n  '
        resolve!
    )


if require.main == module
  do !~>
    await module.exports!

